package cn.huiyunche.driver.controller;

import cn.huiyunche.base.service.constant.TmsUrlConstant;
import cn.huiyunche.base.service.enums.TmsUrlTypeEnum;
import cn.huiyunche.base.service.interfaces.DWaybillService;
import cn.huiyunche.base.service.interfaces.TmsOrderCallHistoryService;
import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.base.service.vo.DWaybillDetailVo;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.UserPositionVo;
import cn.huiyunche.driver.service.DNoticeService;
import cn.huiyunche.driver.service.OrderService;
import cn.huiyunche.driver.service.TmsDDeliveryAuditService;
import cn.huiyunche.driver.service.form.TmsDDeliveryAuditForm;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 运单Controller
 *
 * @author lm
 */
@Controller
@RequestMapping("/waybill")
public class DWaybillController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DWaybillController.class);

    @Autowired
    private DWaybillService dWaybillService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DNoticeService dNoticeService;

    @Autowired
    private TmsDDeliveryAuditService tmsDDeliveryAuditService;

     @Autowired
    private TmsOrderCallHistoryService tmsOrderCallHistoryService;



    /**
     * 首页账单 出车记录数 显示
     *
     * @return
     */
    @RequestMapping(value = "/pageinfo", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Map<String, Object>> getPageInfo() throws Exception {
        Result<Map<String, Object>> result = new Result<>(true, "查询成功！");
        result.setData(this.dWaybillService.getPageInfo());
        return result;
    }

    /**
     * 运单列表
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Map<String, Object>> beQuotedList(@ModelAttribute PageVo page,Integer waybillType) throws Exception {
        LOGGER.info("select dwaybill list params page : {}.", page);
        Result<Map<String, Object>> result = new Result<>(true, "查询成功！");
        result.setData(dWaybillService.getListByPage(page,waybillType));
        return result;
    }

    /**
     * 进行中 运单列表 首页显示运单
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/intransit", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> beQuotedIntransitList(@ModelAttribute PageVo page) throws Exception {
        LOGGER.info("select dwaybill list params page : {}.", page);
        Result<Object> result = new Result<>(true, "查询成功！");
        result.setData(dWaybillService.getIntransitListByPage());
        return result;
    }

    /**
     * 司机交车确认
     * @param id
     * @param attachs
     * @return
     */
    @RequestMapping(value = "/delivery", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<Integer> confirmDelivery(@RequestParam("id") Long id,
                                    @RequestParam("attachs") String attachs, UserPositionVo upv) throws Exception {
        Result<Integer> result = new Result<>(true, "交车照片已上传，请将回单交回!");
        result.setData(dWaybillService.deliveryConfirm(id,upv,attachs));
        return result;
    }

    /**
     * 运单详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result<DWaybillDetailVo> getById(@PathVariable long id) throws Exception {
        Result<DWaybillDetailVo> result = new Result<DWaybillDetailVo>(true, "查询成功！");
        result.setData(dWaybillService.getById(id));
        return result;
    }

    /**
     * 出车记录
     *
     * @return
     */
    @RequestMapping(value = "/done", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Map<String, Object>> beQuotedDoneList(@ModelAttribute PageVo page) throws Exception {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>(true, "查询成功！");
        result.setData(dWaybillService.getDoneByPage(page));
        return result;
    }

    /**
     * Confirm result result.
     *
     * @param id the id
     * @return the result
     */
    @RequestMapping(value = "/confirmResult", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> confirmResult(@RequestParam("id") Long id) {
        Result<T> result = new Result<>(true, "确认回单成功");
        try {
            orderService.confirmResult(id);
        } catch (Exception e) {
            LOGGER.error("confirmResult error : {}", e);
            throw new BusinessException("确认回单失败");
        }
        return result;
    }

    /**
     * 查询当前在途运单
     *
     * @return the result
     */
    @RequestMapping(value = "/currentwaybill", method = RequestMethod.GET)
    @ResponseBody
    public Result<Map<String, Object>> currentWaybill() throws Exception {
        return dWaybillService.currentWaybill();
    }


    /**
     * @param page
     * @param orderCode
     * @param waybillStatus
     * @param beginDate
     * @param endDate
     * @return
     * @Title: 根据订单号查询已交车的运单列表
     * @Description: TODO
     * @return: Result<Map<String,Object>>
     */
    @RequestMapping(value = "/listDelivery", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Map<String, Object>> beQuotedDeliveryList(@ModelAttribute PageVo page,
                                                     @RequestParam("orderCode") String orderCode, @RequestParam("waybillStatus") String waybillStatus,
                                                     @RequestParam("beginDate") String beginDate, @RequestParam("endDate") String endDate) throws Exception {
        LOGGER.info("select dwaybill list params page : {},ordercode:{},waybillStatus:{}，beginDate:{},endDate:{}.", page, orderCode,waybillStatus,beginDate,endDate);
        Result<Map<String, Object>> result = new Result<>(true, "查询成功！");
        result.setData(dWaybillService.getDeliveryListByPage(page, orderCode,waybillStatus, beginDate, endDate));
        return result;
    }


    /**
     * @return
     * @Title: 设置运单审核
     * @Description: TODO
     * @return: Result<T>
     */
    @RequestMapping(value = "/checkDelivery", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> checkDelivery(TmsDDeliveryAuditForm form) {
        Result<T> result = new Result<>(true, "运单审核操作成功");
        try {
            tmsDDeliveryAuditService.save(form);
        } catch (Exception e) {
            LOGGER.error("confirmResult error : {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * @param page
     * @param orderCode
     * @return
     * @Title: 查询所有待发车和在途的订单
     * @Description: TODO
     * @return: Result<Map<String,Object>>
     */
    @RequestMapping(value = "/listintransit", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Map<String, Object>> beQuotedintransitList(@ModelAttribute PageVo page,
                                                      @RequestParam("orderCode") String orderCode) throws Exception {
        LOGGER.info("select dwaybill list params page : {},ordercode:{}", page, orderCode);
        Result<Map<String, Object>> result = new Result<>(true, "查询成功！");
        result.setData(dWaybillService.getListByCodePage(page, orderCode));
        return result;
    }

    /**
     * @param id
     * @return
     * @Title: 打开照片锁定
     * @Description: TODO
     * @return: Result<T>
     */
    @RequestMapping(value = "/openCheckPic", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> openCheckLocalPic(@RequestParam("id") Long id) {
        Result<T> result = new Result<>(true, "运单审核操作成功");
        try {
            dWaybillService.updateWaybillCheckLocalPIC(id, true);
        } catch (Exception e) {
            LOGGER.error("confirmResult error : {}", e);
            throw new BusinessException("运单打开照片锁定操作失败");
        }
        return result;
    }

    /**
     * @param id
     * @return
     * @Title: 关闭照片锁定
     * @Description: TODO
     * @return: Result<T>
     */
    @RequestMapping(value = "/closeCheckPic", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> closeCheckLocalPic(@RequestParam("id") Long id) {
        Result<T> result = new Result<>(true, "运单审核操作成功");
        try {
            dWaybillService.updateWaybillCheckLocalPIC(id, false);
        } catch (Exception e) {
            LOGGER.error("confirmResult error : {}", e);
            throw new BusinessException("运单关闭照片锁定操作失败");
        }
        return result;
    }

    /**
     * 运单列表
     *
     * @param pageVo
     * @param orderCode
     * @param phone
     * @return
     */
    @RequestMapping(value = "/waybilllist", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> waybillList(PageVo pageVo, String orderCode, String phone) {
        Result<Object> result = new Result<>(true, "查询成功");
        try {
            result.setData(dWaybillService.getWaybillListByOrderCodeAndPhone(pageVo, orderCode, phone));
        } catch (Exception e) {
            LOGGER.error("waybillList error : {}", e);
            throw new BusinessException("查询失败");
        }
        return result;
    }


    /**
     * 从TMS抓取单条订单
     *
     *
     * @param orderCode
     * @return
             */
    @RequestMapping(value = "/importSingleOrder", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> importSingleOrder(@RequestParam("orderCode")String orderCode) {
        Result<Object> result = new Result<>(true, "查询成功");
        LOGGER.info(" DWaybillController.importSingleOrder orderCode: {}", orderCode);
        try {
            final String url = TmsUrlConstant.PULL_SINGLE_ORDER;
            Map<String, Object> paramsMap = new HashedMap<>();
            paramsMap.put("orderCode", orderCode);
            String resultStr = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_SINGLE_ORDER.getValue(), paramsMap, 30000);
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                String data = jsonObject.getString("data");
                if (StringUtils.isNotBlank(data)) {
                    List<TmsOrder> tmsOrders = JSONArray.parseArray(data, TmsOrder.class);
                    orderService.handleTmsOrders(tmsOrders);
                    result.setData(tmsOrders.get(0));
                }
            }else{
                result.setMessage("查无数据");
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 推送价格到tms
     *
     * @param orderCode
     * @return
     */
    @RequestMapping(value = "/pushPrice2tms", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> pushPrice2tms(@RequestParam("orderCode")String orderCode) {
        Result<Object> result = new Result<>(true, "推送成功");
        LOGGER.info(" DWaybillController.pushPrice2tms orderCode: {}", orderCode);
        try {
            //dWaybillService.pushPrice2tms(orderCode);

        } catch (Exception e) {
            LOGGER.error("pushPrice2tms error : {}", e);
            throw new BusinessException("推送失败");
        }
        return result;
    }

    /**
     * 查询急发单列表（web端）
     *
     * @param orderCode
     * @return
     */
    @RequestMapping(value = "/quickDispatchList",method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> quickDispatchList(@ModelAttribute PageVo page,
                                     @RequestParam("orderCode") String orderCode,
                                     @RequestParam("beginDate") String beginDate,
                                     @RequestParam("endDate") String endDate,
                                     @RequestParam("waybillType") Integer waybillType){
        LOGGER.info("select quickDispatchList params page : {},ordercode:{},waybillType:{},beginDate:{},endDate:{}.", page, orderCode,waybillType,beginDate,endDate);
        Result<Object> result = new Result<>(true,"查询成功");
        try {

            result.setData(dWaybillService.getQuickDispatchList(page,orderCode,waybillType, beginDate, endDate));
        } catch (Exception e) {
            LOGGER.error("query quickDispatchList error : {}",e);
            throw new BusinessException("查询急发单列表出错 web");
        }
        return result;
    }

    /**
     * 标记订单为急发单
     * @param orderId 订单id
     * @param extraCost 附加费
     * @param specialRequired 特殊要求
     * @param waybillType 运单类型
     * @return
     */
    @RequestMapping(value = "/markQuickDispatch",method = RequestMethod.POST)
    public
    @ResponseBody
    Result<Object> markQuickDispatch(@RequestParam("orderId") Long orderId,
                                     @RequestParam("extraCost") String extraCost,
                                     @RequestParam("specialRequired") String specialRequired,
                                     @RequestParam("waybillType") Integer waybillType){
        LOGGER.info(" markQuickDispatch params orderId : {}, extraCost:{}, specialRequired:{},waybillType:{}.", orderId, extraCost, specialRequired,waybillType);
        Result<Object> result = new Result<>(true, "标记急发单操作成功");
        try {
        	
            if (waybillType != 10 && waybillType != 20){
            	result.setMessage("状态错误");
        	}
            dWaybillService.markQuickDispatch(orderId, extraCost, specialRequired, waybillType);      
            
        } catch (Exception e) {
            LOGGER.error("query quickDispatchList error : {}",e);
            throw new BusinessException("标记急发单操作出错");
        }
        return result;
    }

    /**
     * 司机发现急发单，会进行抢单
     * @param orderId 订单id
     * @return
     */
    @RequestMapping(value = "/competeQuickOrderList",method = RequestMethod.POST)
    public
    @ResponseBody
    Result<Object> competeQuickOrderList(@RequestParam("orderId") Long orderId){
        LOGGER.info(" competeQuickOrderList params orderId : {}.", orderId);
        Result<Object> result = new Result<>(true, "司机抢单成功");
        try {
            dWaybillService.competeQuickOrderList(orderId);
        } catch (Exception e) {
            LOGGER.error("competeQuickOrderList error : {}",e);
            result.setSuccess(false);
            result.setMessage("司机抢单失败");
            throw new BusinessException(e.getMessage());
        }
        return result;
    }
}
